/**
 * 状态工具类
 * 统一管理系统中所有状态的显示和转换
 */
class StatusUtils {
    
    // 缓存状态配置
    static statusConfig = null;
    
    /**
     * 初始化状态配置
     */
    static async init() {
        try {
            const response = await fetch('/ercms/api/status-config/all');
            if (response.ok) {
                this.statusConfig = await response.json();
                console.log('状态配置加载成功:', this.statusConfig);
            } else {
                console.error('加载状态配置失败:', response.status);
            }
        } catch (error) {
            console.error('加载状态配置出错:', error);
        }
    }
    
    /**
     * 获取事件状态中文名称
     */
    static getEventStatusText(status) {
        if (!this.statusConfig) {
            return this.getDefaultEventStatusText(status);
        }
        return this.statusConfig.eventStatuses[status] || status;
    }
    
    /**
     * 获取响应者状态中文名称
     */
    static getResponderStatusText(status) {
        if (!this.statusConfig) {
            return this.getDefaultResponderStatusText(status);
        }
        return this.statusConfig.responderStatuses[status] || status;
    }
    
    /**
     * 获取用户状态中文名称
     */
    static getUserStatusText(status) {
        if (!this.statusConfig) {
            return this.getDefaultUserStatusText(status);
        }
        return this.statusConfig.userStatuses[status] || status;
    }
    
    /**
     * 获取资源状态中文名称
     */
    static getResourceStatusText(status) {
        if (!this.statusConfig) {
            return this.getDefaultResourceStatusText(status);
        }
        return this.statusConfig.resourceStatuses[status] || status;
    }
    
    /**
     * 获取安全状态中文名称
     */
    static getSafetyStatusText(status) {
        if (!this.statusConfig) {
            return this.getDefaultSafetyStatusText(status);
        }
        return this.statusConfig.safetyStatuses[status] || status;
    }
    
    /**
     * 获取优先级中文名称
     */
    static getPriorityText(priority) {
        if (!this.statusConfig) {
            return this.getDefaultPriorityText(priority);
        }
        return this.statusConfig.priorities[priority] || priority;
    }
    
    /**
     * 获取严重程度中文名称
     */
    static getSeverityText(severity) {
        if (!this.statusConfig) {
            return this.getDefaultSeverityText(severity);
        }
        return this.statusConfig.severities[severity] || severity;
    }
    
    /**
     * 获取状态样式类
     */
    static getStatusClass(status) {
        const statusClasses = {
            'PENDING': 'bg-warning',
            'ASSIGNED': 'bg-info',
            'IN_PROGRESS': 'bg-primary',
            'RESOLVED': 'bg-success',
            'CLOSED': 'bg-secondary',
            'ACCEPTED': 'bg-primary',
            'EN_ROUTE': 'bg-primary',
            'ARRIVED': 'bg-primary',
            'COMPLETED': 'bg-success',
            'RETURNING': 'bg-success',
            'AVAILABLE': 'bg-success',
            'BUSY': 'bg-warning',
            'OFFLINE': 'bg-secondary',
            'IN_USE': 'bg-primary',
            'MAINTENANCE': 'bg-warning',
            'RETIRED': 'bg-secondary',
            'SAFE': 'bg-success',
            'CAUTION': 'bg-warning',
            'DANGER': 'bg-danger',
            'SOS': 'bg-danger'
        };
        return statusClasses[status] || 'bg-secondary';
    }
    
    /**
     * 获取状态颜色
     */
    static getStatusColor(status) {
        const statusColors = {
            'PENDING': '#ffc107',
            'ASSIGNED': '#17a2b8',
            'IN_PROGRESS': '#007bff',
            'RESOLVED': '#28a745',
            'CLOSED': '#6c757d',
            'ACCEPTED': '#007bff',
            'EN_ROUTE': '#007bff',
            'ARRIVED': '#007bff',
            'COMPLETED': '#28a745',
            'RETURNING': '#28a745',
            'AVAILABLE': '#28a745',
            'BUSY': '#ffc107',
            'OFFLINE': '#6c757d',
            'IN_USE': '#007bff',
            'MAINTENANCE': '#fd7e14',
            'RETIRED': '#6c757d',
            'SAFE': '#28a745',
            'CAUTION': '#ffc107',
            'DANGER': '#fd7e14',
            'SOS': '#dc3545'
        };
        return statusColors[status] || '#6c757d';
    }
    
    /**
     * 创建状态徽章HTML
     */
    static createStatusBadge(status, type = 'event') {
        let text = status;
        let cssClass = this.getStatusClass(status);
        
        switch (type) {
            case 'event':
                text = this.getEventStatusText(status);
                break;
            case 'responder':
                text = this.getResponderStatusText(status);
                break;
            case 'user':
                text = this.getUserStatusText(status);
                break;
            case 'resource':
                text = this.getResourceStatusText(status);
                break;
            case 'safety':
                text = this.getSafetyStatusText(status);
                break;
            case 'priority':
                text = this.getPriorityText(status);
                break;
            case 'severity':
                text = this.getSeverityText(status);
                break;
        }
        
        return `<span class="badge ${cssClass}">${text}</span>`;
    }
    
    /**
     * 创建带颜色的状态文本
     */
    static createStatusText(status, type = 'event') {
        let text = status;
        let color = this.getStatusColor(status);
        
        switch (type) {
            case 'event':
                text = this.getEventStatusText(status);
                break;
            case 'responder':
                text = this.getResponderStatusText(status);
                break;
            case 'user':
                text = this.getUserStatusText(status);
                break;
            case 'resource':
                text = this.getResourceStatusText(status);
                break;
            case 'safety':
                text = this.getSafetyStatusText(status);
                break;
            case 'priority':
                text = this.getPriorityText(status);
                break;
            case 'severity':
                text = this.getSeverityText(status);
                break;
        }
        
        return `<span style="color: ${color}; font-weight: bold;">${text}</span>`;
    }
    
    // 默认状态映射（作为备用）
    static getDefaultEventStatusText(status) {
        const map = {
            'PENDING': '待处理',
            'ASSIGNED': '已分配',
            'IN_PROGRESS': '处理中',
            'RESOLVED': '已解决',
            'CLOSED': '已关闭'
        };
        return map[status] || status;
    }
    
    static getDefaultResponderStatusText(status) {
        const map = {
            'ASSIGNED': '已指派',
            'ACCEPTED': '已接受',
            'EN_ROUTE': '正在前往',
            'ARRIVED': '到达现场',
            'IN_PROGRESS': '开始处理',
            'COMPLETED': '完成任务',
            'RETURNING': '返程中'
        };
        return map[status] || status;
    }
    
    static getDefaultUserStatusText(status) {
        const map = {
            'AVAILABLE': '可用',
            'BUSY': '忙碌',
            'OFFLINE': '离线'
        };
        return map[status] || status;
    }
    
    static getDefaultResourceStatusText(status) {
        const map = {
            'AVAILABLE': '可用',
            'IN_USE': '使用中',
            'MAINTENANCE': '维护中',
            'RETIRED': '已报废'
        };
        return map[status] || status;
    }
    
    static getDefaultSafetyStatusText(status) {
        const map = {
            'SAFE': '安全',
            'CAUTION': '注意',
            'DANGER': '危险',
            'SOS': '紧急求助'
        };
        return map[status] || status;
    }
    
    static getDefaultPriorityText(priority) {
        const map = {
            'LOW': '低',
            'MEDIUM': '中',
            'HIGH': '高',
            'CRITICAL': '危急'
        };
        return map[priority] || priority;
    }
    
    static getDefaultSeverityText(severity) {
        const map = {
            'MINOR': '轻微',
            'MODERATE': '一般',
            'SEVERE': '严重',
            'CRITICAL': '危急'
        };
        return map[severity] || severity;
    }
    
    /**
     * 验证状态是否有效
     */
    static isValidEventStatus(status) {
        if (!this.statusConfig) {
            return ['PENDING', 'ASSIGNED', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'].includes(status);
        }
        return this.statusConfig.eventStatuses.hasOwnProperty(status);
    }
    
    static isValidResponderStatus(status) {
        if (!this.statusConfig) {
            return ['ASSIGNED', 'ACCEPTED', 'EN_ROUTE', 'ARRIVED', 'IN_PROGRESS', 'COMPLETED', 'RETURNING'].includes(status);
        }
        return this.statusConfig.responderStatuses.hasOwnProperty(status);
    }
    
    static isValidUserStatus(status) {
        if (!this.statusConfig) {
            return ['AVAILABLE', 'BUSY', 'OFFLINE'].includes(status);
        }
        return this.statusConfig.userStatuses.hasOwnProperty(status);
    }
    
    static isValidResourceStatus(status) {
        if (!this.statusConfig) {
            return ['AVAILABLE', 'IN_USE', 'MAINTENANCE', 'RETIRED'].includes(status);
        }
        return this.statusConfig.resourceStatuses.hasOwnProperty(status);
    }
    
    static isValidSafetyStatus(status) {
        if (!this.statusConfig) {
            return ['SAFE', 'CAUTION', 'DANGER', 'SOS'].includes(status);
        }
        return this.statusConfig.safetyStatuses.hasOwnProperty(status);
    }
    
    /**
     * 获取所有状态选项（用于下拉框）
     */
    static getEventStatusOptions() {
        if (!this.statusConfig) {
            return [
                { value: 'PENDING', text: '待处理' },
                { value: 'ASSIGNED', text: '已分配' },
                { value: 'IN_PROGRESS', text: '处理中' },
                { value: 'RESOLVED', text: '已解决' },
                { value: 'CLOSED', text: '已关闭' }
            ];
        }
        
        return Object.entries(this.statusConfig.eventStatuses).map(([value, text]) => ({
            value: value,
            text: text
        }));
    }
    
    static getResponderStatusOptions() {
        if (!this.statusConfig) {
            return [
                { value: 'ASSIGNED', text: '已指派' },
                { value: 'ACCEPTED', text: '已接受' },
                { value: 'EN_ROUTE', text: '正在前往' },
                { value: 'ARRIVED', text: '到达现场' },
                { value: 'IN_PROGRESS', text: '开始处理' },
                { value: 'COMPLETED', text: '完成任务' },
                { value: 'RETURNING', text: '返程中' }
            ];
        }
        
        return Object.entries(this.statusConfig.responderStatuses).map(([value, text]) => ({
            value: value,
            text: text
        }));
    }
    
    static getUserStatusOptions() {
        if (!this.statusConfig) {
            return [
                { value: 'AVAILABLE', text: '可用' },
                { value: 'BUSY', text: '忙碌' },
                { value: 'OFFLINE', text: '离线' }
            ];
        }
        
        return Object.entries(this.statusConfig.userStatuses).map(([value, text]) => ({
            value: value,
            text: text
        }));
    }
    
    static getResourceStatusOptions() {
        if (!this.statusConfig) {
            return [
                { value: 'AVAILABLE', text: '可用' },
                { value: 'IN_USE', text: '使用中' },
                { value: 'MAINTENANCE', text: '维护中' },
                { value: 'RETIRED', text: '已报废' }
            ];
        }
        
        return Object.entries(this.statusConfig.resourceStatuses).map(([value, text]) => ({
            value: value,
            text: text
        }));
    }
    
    static getPriorityOptions() {
        if (!this.statusConfig) {
            return [
                { value: 'LOW', text: '低' },
                { value: 'MEDIUM', text: '中' },
                { value: 'HIGH', text: '高' },
                { value: 'CRITICAL', text: '危急' }
            ];
        }
        
        return Object.entries(this.statusConfig.priorities).map(([value, text]) => ({
            value: value,
            text: text
        }));
    }
    
    static getSeverityOptions() {
        if (!this.statusConfig) {
            return [
                { value: 'MINOR', text: '轻微' },
                { value: 'MODERATE', text: '一般' },
                { value: 'SEVERE', text: '严重' },
                { value: 'CRITICAL', text: '危急' }
            ];
        }
        
        return Object.entries(this.statusConfig.severities).map(([value, text]) => ({
            value: value,
            text: text
        }));
    }
}

// 页面加载时自动初始化
document.addEventListener('DOMContentLoaded', function() {
    StatusUtils.init();
});

// 导出到全局作用域
window.StatusUtils = StatusUtils; 